package com.codeanalysissys.backend.javascript;

import com.codeanalysissys.backend.graphs.pdg.ControlDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.DataDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.ProgramDependeceGraph;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class JavaScriptPDBGuilder {
    /**
     * Builds and returns Program Dependence Graphs (PDG) for each given JavaScript file.
     */
    public static ProgramDependeceGraph[] buildForAll(String[] jsFilePaths) throws IOException {
        File[] jsFiles = new File[jsFilePaths.length];
        for (int i = 0; i < jsFiles.length; ++i)
            jsFiles[i] = new File(jsFilePaths[i]);
        return buildForAll(jsFiles);
    }

    /**
     * Builds and returns Program Dependence Graphs (PDG) for each given JavaScript file.
     */
    public static ProgramDependeceGraph[] buildForAll(File[] jsFiles) throws IOException {

        ControlDependenceGraph[] ctrlSubgraphs;
        ctrlSubgraphs = new ControlDependenceGraph[jsFiles.length];
        for (int i = 0; i < jsFiles.length; ++i)
            ctrlSubgraphs[i] = JavaScriptCDGBuilder.build(jsFiles[i]);
        //
//        DataDependenceGraph[] dataSubgraphs = new DataDependenceGraph[jsFiles.length];
        DataDependenceGraph[] dataSubgraphs = JavaScriptDDGBuilder.buildForAll(jsFiles);
        //
        // Join the subgraphs into PDGs
        ProgramDependeceGraph[] pdgArray = new ProgramDependeceGraph[jsFiles.length];
        for (int i = 0; i < jsFiles.length; ++i) {
            pdgArray[i] = new ProgramDependeceGraph(jsFiles[i].getName(),
                    ctrlSubgraphs[i], dataSubgraphs[i]);
        }

        return pdgArray;
    }

    public static ProgramDependeceGraph build(InputStream content) throws IOException {
        return new ProgramDependeceGraph(JavaScriptCDGBuilder.build(content), JavaScriptDDGBuilder.build(content));
    }
}
